/**
 * @author Created by shuaqiu on 2017-05-30.
 */

import * as React from 'react';
import {DragSource, DropTarget} from 'react-dnd';

import dndSource from '../../dnd/dndSource';
import dndTarget from '../../dnd/dndTarget';
import dndItemTypes from '../../dnd/dndItemTypes';

import store from '../../store/index';
import {ActionType} from '../../store/ActionType';

import {IView} from '../../types/IView';
import isParentView from '../../types/IParentView';

export interface HierarchyNodeProps {
  view: IView;
  selectedView: IView;
  isExpanded: boolean;
  onToggle: (view: IView) => void;
  connectDragSource?: (elem: JSX.Element) => JSX.Element | null;
  connectDropTarget?: (elem: JSX.Element) => JSX.Element | null;
}

class HierarchyNode extends React.Component<HierarchyNodeProps, undefined> {
  render() {
    const {view, selectedView, connectDragSource, connectDropTarget} = this.props;
    const isSelect = selectedView && selectedView.id === view.id;
    const className = `Hierarchy-item-name${isSelect ? ' selected' : ''}`;
    return connectDragSource(connectDropTarget(
      <div className={className} onClick={this.handleClick}>
        {this.renderViewToggle(view)}
        <span>{`${view.viewType}(${view.attrVals.id})`}</span>
      </div>
    ));
  }

  private renderViewToggle(view: IView) {
    if (!isParentView(view) || view.children.length === 0) {
      return (
        <span className="Hierarchy-toggle-empty">&nbsp;</span>
      );
    }

    const onToggle = () => {
      this.props.onToggle(view);
    };

    const content = this.props.isExpanded ? '-' : '+';
    return (
      <span className="Hierarchy-toggle" onClick={onToggle}>{content}</span>
    );
  }

  private handleClick = () => {
    const view = this.props.view;
    // 点击就选中
    store.dispatch({
      type: ActionType.SELECT_VIEW,
      designId: view.designId,
      view
    });
  }
}

export default DragSource(dndItemTypes.WIDGET, dndSource.source, dndSource.collect)(
  DropTarget(dndItemTypes.WIDGET, dndTarget.target, dndTarget.collect)(HierarchyNode)
);
